import logging
import math
from typing import Optional, List

from fastapi import APIRouter, Depends, Query, Path
from pydantic import Field, BaseModel
from sqlalchemy import text
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.orm import Session
from commons.BaseResponse import BaseResponse
from commons.PaginationBase import PaginationBase
from datebase import get_db
from utils.EncryptionUtil import oauth2_scheme, EncryptionMiddleware

data_check_head_router = APIRouter(prefix="/material/checkHead", tags=["物料盘点管理"],
                                   dependencies=[Depends(oauth2_scheme)])


class MaterialInQuerySearch(PaginationBase):
    # 筛选条件
    fsiteNo: Optional[str] = Field("", description="站点编号")
    ftakedateStart: Optional[str] = Field("", description="入库开始日期(yyyyMMdd)")
    ftakedateEnd: Optional[str] = Field("", description="入库结束日期(yyyyMMdd)")
    fbilltype: Optional[str] = Field("", description="单据类型编码(3表示采购入库)")
    fmrkuser: Optional[str] = Field("", description="制单人")
    fstockno: Optional[str] = Field("", description="仓库编号")
    fbillno: Optional[str] = Field("", description="单据编号(支持前缀匹配)")
    fbillstate: Optional[str] = Field("", description="单据状态编码")


class MaterialCheckDetail(BaseModel):
    """物料盘点明细"""
    fline: int = Field(..., description="明细行号")
    fgoodno: str = Field(..., description="物料编号")
    fbalqty: str = Field(..., description="账面数量")
    fpdqty: str = Field(..., description="盘点数量")
    flosqty: str = Field(..., description="盈亏数量")
    fpduser: str = Field(..., description="盘点人")
    fpddate: str = Field(..., description="盘点日期(yyyy-MM-dd)")
    fprocdate: Optional[str] = Field(None, description="处理日期")


class MaterialCheckCreate(BaseModel):
    """物料盘点新增请求参数"""
    fbillno: str = Field(..., description="单据编号")
    fpddate: str = Field(..., description="盘点日期(yyyy-MM-dd)")
    fpduser: str = Field(..., description="盘点人")
    fsiteNo: str = Field(..., description="站点编号")
    fstockno: str = Field(..., description="仓库编号")
    fbilltype: Optional[str] = Field("1", description="单据类型编码")
    fexplanation: Optional[str] = Field("", description="盘点说明")
    details: List[MaterialCheckDetail] = Field(..., description="盘点明细列表")


@data_check_head_router.get("/list", summary="物料采购入库查询接口")
def list_checkhead(search: MaterialInQuerySearch = Query(), db: Session = Depends(get_db)):
    param = {}
    sql = "select count(1) from i_tc_mrk_head where fbilltype=3"
    if search.fsiteNo != "":
        sql = sql + " and fsite_no = :site_no "
        param["site_no"] = search.fsiteNo
    if search.fbillno != "":
        sql = sql + " and fbillno like concat('%', :fbillno ,'%')"
        param["fbillno"] = search.fbillno
    if search.fmrkuser != "":
        sql = sql + " and fmrkuser = :fmrkuser "
        param["fmrkuser"] = search.fmrkuser
    if search.fstockno != "":
        sql = sql + " and fstockno = :fstockno "
        param["fstockno"] = search.fstockno
    if search.fbilltype != "":
        sql = sql + " and fbilltype = :fbilltype "
        param["fbilltype"] = search.fbilltype
    if search.fbillstate != "":
        sql = sql + " and fbillstate = :fbillstate "
        param["fbillstate"] = search.fbillstate
    if (search.ftakedateStart != "") and (search.ftakedateEnd != ""):
        sql = sql + " and to_char(fmrkdate,'yyyymmdd') between :ftakedateStart  and :ftakedateEnd "
        param["ftakedateStart"] = search.ftakedateStart
        param["ftakedateEnd"] = search.ftakedateEnd
    count = db.execute(text(sql), param).scalar()

    param = {}
    sql = "select fbillno,fsite_no,fmrkuser,to_char(fmrkdate,'yyyy-mm-dd HH24:MI:SS') fmrkdate,fstockno,fitemcount,fpiececount,ftotalamt,"
    sql = sql + " fexplanation,to_char(fupddate,'yyyy-mm-dd HH24:MI:SS') fupddate,foperator,to_char(fcheckdate,'yyyy-mm-dd HH24:MI:SS') fcheckdate,fcheckuser,fbillstate,fbilltype"
    sql = sql + " from i_tc_mrk_head where fbilltype=3"
    if search.fsiteNo != "":
        sql = sql + " and fsite_no = :site_no "
        param["site_no"] = search.fsiteNo
    if search.fbillno != "":
        sql = sql + " and fbillno like concat('%', :fbillno ,'%')"
        param["fbillno"] = search.fbillno
    if search.fmrkuser != "":
        sql = sql + " and fmrkuser = :fmrkuser "
        param["fmrkuser"] = search.fmrkuser
    if search.fstockno != "":
        sql = sql + " and fstockno = :fstockno "
        param["fstockno"] = search.fstockno
    if search.fbilltype != "":
        sql = sql + " and fbilltype = :fbilltype "
        param["fbilltype"] = search.fbilltype
    if search.fbillstate != "":
        sql = sql + " and fbillstate = :fbillstate "
        param["fbillstate"] = search.fbillstate
    if (search.ftakedateStart != "") and (search.ftakedateEnd != ""):
        sql = sql + " and to_char(fmrkdate,'yyyymmdd') between :ftakedateStart  and :ftakedateEnd "
        param["ftakedateStart"] = search.ftakedateStart
        param["ftakedateEnd"] = search.ftakedateEnd
    if search.order == "desc":
        sql = sql + " order by  fmrkdate,fbillno desc "
    else:
        sql = sql + " order by  fmrkdate,fbillno "
    sql = sql + " limit :limit offset :offset "
    param["limit"] = search.limit
    param["offset"] = search.offset
    data = db.execute(text(sql), param).fetchall()

    # details 明细列表
    param = {}
    sql_3 = " select b.fbillno,b.fline,b.frfidbarcode,b.fgoodno,b.fbuyprice,b.fqty,b.ftotamt,"
    sql_3 = sql_3 + " b.fboxbarcode,b.fcabbarcode,b.foperator,b.fupddate,b.fmemo,b.fprocdate,"
    sql_3 = sql_3 + " c.fgoodname"
    sql_3 = sql_3 + " from i_tc_mrk_head a  "
    sql_3 = sql_3 + " left join i_tc_mrk_detail b on a.fbillno=b.fbillno"
    sql_3 = sql_3 + " left join i_ts_good_info c  on b.fgoodno=c.fgoodno"
    sql_3 = sql_3 + " where fbilltype=3"
    if search.fsiteNo != "":
        sql_3 = sql_3 + " and a.fsite_no = :fsiteNo "
        param["fsiteNo"] = search.fsiteNo
    if search.fbillno != "":
        sql_3 = sql_3 + " and a.fbillno like concat('%', :fbillno ,'%')"
        param["fbillno"] = search.fbillno
    if search.fmrkuser != "":
        sql_3 = sql_3 + " and a.fmrkuser = :fmrkuser "
        param["fmrkuser"] = search.fmrkuser
    if search.fstockno != "":
        sql_3 = sql_3 + " and a.fstockno = :fstockno "
        param["fstockno"] = search.fstockno
    if search.fbilltype != "":
        sql_3 = sql_3 + " and a.fbilltype = :fbilltype "
        param["fbilltype"] = search.fbilltype
    if search.fbillstate != "":
        sql_3 = sql_3 + " and a.fbillstate = :fbillstate "
        param["fbillstate"] = search.fbillstate
    if (search.ftakedateStart != "") and (search.ftakedateEnd != ""):
        sql_3 = sql_3 + " and to_char(a.fmrkdate,'yyyymmdd') between :ftakedateStart  and :ftakedateEnd "
        param["ftakedateStart"] = search.ftakedateStart
        param["ftakedateEnd"] = search.ftakedateEnd
    sql_3 = sql_3 + " order by b.fbillno,b.fline"
    data_detail = db.execute(text(sql_3), param).fetchall()

    data_list = []
    for key in range(len(data)):
        d1 = {}
        d1['fbillno'] = data[key][0]
        d1['fsiteno'] = data[key][1]
        d1['fmrkuser'] = data[key][2]
        d1['fmrkdate'] = data[key][3]
        d1['fstockno'] = data[key][4]
        d1['fitemcount'] = data[key][5]
        d1['fpiececount'] = data[key][6]
        d1['ftotalamt'] = data[key][7]
        d1['fexplanation'] = data[key][8]
        d1['fupddate'] = data[key][9]
        d1['foperator'] = data[key][10]
        d1['fcheckdate'] = data[key][11]
        d1['fcheckuser'] = data[key][12]
        d1['fbillstate'] = data[key][13]
        d1['fbilltype'] = data[key][14]
        sbillno = data[key][0]
        # 过滤数据
        filtered_rows = [row for row in data_detail if row[0] == sbillno]
        detail_list = []
        for j1 in range(len(filtered_rows)):
            tupddate = ""
            try:
                tupddate = filtered_rows[j1][10].strftime('%Y-%m-%dT%H:%M:%S')
            except Exception as e:
                print(e)
            if (tupddate == ""):
                tupddate = None
            tprocdate = ""
            try:
                tprocdate = filtered_rows[j1][12].strftime('%Y-%m-%dT%H:%M:%S')
            except Exception as e:
                print(e)
            if (tprocdate == ""):
                tprocdate = None
            d2 = {}
            d2['fbillno'] = filtered_rows[j1][0]
            d2['fline'] = filtered_rows[j1][1]
            d2['frfidbarcode'] = filtered_rows[j1][2]
            d2['fgoodno'] = filtered_rows[j1][3]
            d2['fbuyprice'] = filtered_rows[j1][4]
            d2['fqty'] = filtered_rows[j1][5]
            d2['ftotamt'] = filtered_rows[j1][6]
            d2['fboxbarcode'] = filtered_rows[j1][7]
            d2['fcabbarcode'] = filtered_rows[j1][8]
            d2['foperator'] = filtered_rows[j1][9]
            d2['fupddate'] = tupddate
            d2['fmemo'] = filtered_rows[j1][11]
            d2['fprocdate'] = tprocdate
            d2['fgoodname'] = filtered_rows[j1][13]
            detail_list.append(d2)

        d1["details"] = detail_list
        data_list.append(d1)

    info_dict = {"list": data_list, "limit": int(search.offset), "page": int(search.pageIndex),
                 "pages": (count + search.limit - 1) // search.limit,
                 "total": count}
    return BaseResponse.success(data=info_dict)


@data_check_head_router.post("/create", summary="物料盘点新增接口")
def create_checkhead(create: MaterialCheckCreate, db: Session = Depends(get_db)):
    try:
        fitemcount = 0
        fpiececount = 0
        ftotalamt = 0
        # 返回内容
        d1 = {}
        detail_list = []
        fbillno = create.fbillno
        with db.begin():
            details = create.details
            for detail in details:
                sql = "insert into i_tc_check_detail(fbillno,fline,fgoodno,fbalqty,fpdqty,flosqty,fpduser,fpddate,fprocdate)"
                sql = sql + " values( :fbillno , :fline , :fgoodno , :fbalqty , :fpdqty , :flosqty , :fpduser , ：fpddate , ：fprocdate )"
                db.execute(text(sql), {
                    "fbillno": fbillno,
                    "fline": detail.fline,
                    "fgoodno": detail.fgoodno,
                    "fbalqty": detail.fbalqty,
                    "fpdqty": detail.fpdqty,
                    "flosqty": detail.flosqty,
                    "fpduser": detail.fpduser,
                    "fpddate": detail.fpddate,
                    "fprocdate": detail.fprocdate
                })
                fitemcount = fitemcount + 1
                fpiececount = fpiececount + float(detail.fpdqty)

                # 返回明细
                d2 = {}
                d2['fbillno'] = fbillno
                d2['fline'] = detail.fline
                d2['fgoodno'] = detail.fgoodno
                d2['fbalqty'] = detail.fbalqty
                d2['fpdqty'] = detail.fpdqty
                d2['flosqty'] = detail.flosqty
                d2['fpduser'] = detail.fpduser
                d2['fpddate'] = detail.fpddate
                d2['fprocdate'] = detail.fprocdate
                detail_list.append(d2)
            sql = "insert into i_tc_check_head(fbillno,fsite_no,fpduser,fpddate,fstockno,fitemcount,fpiececount,ftotalamt,fexplanation,fupddate,foperator,fbillstate,fbilltype)"
            sql = sql + " values( :fbillno , :fsiteNo , :fpduser , :fpddate , :fstockno , :fitemcount , :fpiececount , :ftotalamt , :fexplanation ,now(), :fpduser ,1, :fbilltype )"
            db.execute(text(sql), {
                "fbillno": fbillno,
                "fsiteNo": create.fsiteNo,
                "fpduser": create.fpduser,
                "fpddate": create.fpddate,
                "fstockno": create.fstockno,
                "fitemcount": fitemcount,
                "fpiececount": fpiececount,
                "ftotalamt": ftotalamt,
                "fexplanation": create.fexplanation,
                "fbilltype": create.fbilltype,
            })
            # 返回
            d1['fbillno'] = fbillno
            d1['fsiteno'] = create.fsiteNo
            d1['fpduser'] = create.fpduser
            d1['fpddate'] = create.fpddate
            d1['fstockno'] = create.fstockno
            d1['fitemcount'] = fitemcount
            d1['fpiececount'] = fpiececount
            d1['ftotalamt'] = float(ftotalamt)
            d1['fexplanation'] = create.fexplanation
            d1['fupddate'] = create.fpddate
            d1['foperator'] = create.fpduser
            d1['fcheckdate'] = None
            d1['fcheckuser'] = None
            d1['fbillstate'] = 1
            d1['fbilltype'] = create.fbilltype
            d1["details"] = detail_list
            return BaseResponse.success(data=d1)
    except SQLAlchemyError as e:
        # 发生异常时自动回滚
        db.rollback()
        # 记录错误日志
        logging.error(f"数据库错误: {str(e)}")
        # 返回错误响应
        return BaseResponse.error(message="数据库操作失败")
    except Exception as e:
        db.rollback()
        logging.error(f"未知错误: {str(e)}")
        return BaseResponse.error(message="令牌过期")


@data_check_head_router.post("/update", summary="物料盘点修改接口")
def update_checkhead(update: MaterialCheckCreate, db: Session = Depends(get_db), token: str = Depends(oauth2_scheme)):
    try:
        fitemcount = 0
        fpiececount = 0
        ftotalamt = 0
        fbillno = update.fbillno
        user_id = EncryptionMiddleware.get_current_user(token)
        with db.begin():
            sql = "delete from i_tc_check_detail where fbillno :fbillno "
            db.execute(text(sql), {
                "fbillno": fbillno,
            })
            details = update.details
            for detail in details:
                sql = "insert into i_tc_check_detail(fbillno,fline,fgoodno,fbalqty,fpdqty,flosqty,fpduser,fpddate,fprocdate)"
                sql = sql + " values( :fbillno , :fline , :fgoodno , :fbalqty , :fpdqty , :flosqty , :fpduser , ：fpddate , ：fprocdate )"
                db.execute(text(sql), {
                    "fbillno": fbillno,
                    "fline": detail.fline,
                    "fgoodno": detail.fgoodno,
                    "fbalqty": detail.fbalqty,
                    "fpdqty": detail.fpdqty,
                    "flosqty": detail.flosqty,
                    "fpduser": detail.fpduser,
                    "fpddate": detail.fpddate,
                    "fprocdate": detail.fprocdate
                })
                fitemcount = fitemcount + 1
                fpiececount = fpiececount + float(detail.fpdqty)
            sql = "update i_tc_check_head "
            sql = sql + " set fstockno= :fstockno ,fbilltype= :fbilltype ,fexplanation= :fexplanation "
            sql = sql + ",fpduser= :fpduser ,fpddate= :fpddate "
            sql = sql + ",fitemcount= :fitemcount ,fpiececount= :fpiececount ,ftotalamt= :ftotalamt "
            sql = sql + ",fupddate=now(),foperator= :userid "
            sql = sql + " where fbillno= :fbillno "
            db.execute(text(sql), {
                "fstockno": update.fstockno,
                "fbilltype": update.fbilltype,
                "fexplanation": update.fexplanation,
                "fpduser": update.fpduser,
                "fpddate": update.fpddate,
                "fitemcount": fitemcount,
                "fpiececount": fpiececount,
                "ftotalamt": ftotalamt,
                "userid": user_id,
                "fbillno": fbillno,
            })
            return BaseResponse.success()
    except SQLAlchemyError as e:
        # 发生异常时自动回滚
        db.rollback()
        # 记录错误日志
        logging.error(f"数据库错误: {str(e)}")
        # 返回错误响应
        return BaseResponse.error(message="数据库操作失败")
    except Exception as e:
        db.rollback()
        logging.error(f"未知错误: {str(e)}")
        return BaseResponse.error(message="令牌过期")


@data_check_head_router.post("/delete/{fbillno}", summary="物料盘点删除接口")
def delete_checkhead(fbillno: str = Path(description="单号"), db: Session = Depends(get_db)):
    try:
        with db.begin():
            sql = "select count(1) from i_tc_check_head where fbillno= :fbillno  and fbillstate>1"
            data = db.execute(text(sql), {
                "fbillno": fbillno,
            }).fetchall()

            if data[0][0] > 0:
                return BaseResponse.error(message="该订单不能删除")
            else:
                sql = "delete from i_tc_check_detail where fbillno= :fbillno "
                db.execute(text(sql), {
                    "fbillno": fbillno
                })
                sql = "delete from i_tc_check_head where fbillno= :fbillno "
                db.execute(text(sql), {
                    "fbillno": fbillno
                })
                return BaseResponse.success()
    except SQLAlchemyError as e:
        # 发生异常时自动回滚
        db.rollback()
        # 记录错误日志
        logging.error(f"数据库错误: {str(e)}")
        # 返回错误响应
        return BaseResponse.error(message="数据库操作失败")
    except Exception as e:
        db.rollback()
        logging.error(f"未知错误: {str(e)}")
        return BaseResponse.error(message="令牌过期")
